package com.qxp.simplerpc.utils;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.*;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;


public class HystrixUtils extends HystrixCommand<String> {
    private static String serviceGroup = "serviceGroup";
    private static String serviceQuery = "serviceQuery";
    private static String service1ThreadPool = "service1ThreadPool";
    private Object instance;
    private Class<?> target;
    private String methodName;
    private Class<?>[] parameterTypes;
    private Object[] args;

    public HystrixUtils(Object instance, Class<?> target, String methodName, Class<?>[] parameterTypes, Object[] args) {
        super(
            Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(serviceGroup))
                    .andCommandKey(HystrixCommandKey.Factory.asKey(serviceQuery))
                    .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(service1ThreadPool))
                    .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                            .withCoreSize(20))//服务线程池数量
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                            .withCircuitBreakerErrorThresholdPercentage(60)//熔断器关闭到打开阈值
                            .withCircuitBreakerSleepWindowInMilliseconds(3000)//熔断器打开到关闭的时间窗长度
        ));
        this.instance = instance;
        this.target = target;
        this.methodName = methodName;
        this.parameterTypes = parameterTypes;
        this.args = args;

    }

    @Override
    protected String run() throws Exception {
        // get instance from spring content
        //Object instance = applicationContext.getBean(target);
        Method method = target.getMethod(methodName,parameterTypes);
        Object obj = method.invoke(instance,args);
        if(obj instanceof String){
            return (String)obj;
        }
        //runnable.run();
        return JSON.toJSONString(obj);
    }

    @Override
    protected String getFallback() {
        return super.getFallback();
    }
}
